<template>
  <div>
    <router-view></router-view>
    <van-tabbar v-model="active" active-color="#ee0a24" inactive-color="#000">
      <van-tabbar-item replace to="/shops_index" icon="shop-o">商品分类</van-tabbar-item>
      <van-tabbar-item replace to="/shops_index/shops_goodshow" icon="shop-o">商品</van-tabbar-item>
      <van-tabbar-item replace to="/shops_index/shops_chat" icon="chat-o">消息</van-tabbar-item>
      <van-tabbar-item replace to="/shops_index/shops_order" icon="orders-o" 
        >订单</van-tabbar-item
      >
      <van-tabbar-item
        replace
        to="/shops_index/shops_userinfo"
        icon="user-circle-o"
        >个人主页</van-tabbar-item
      >
    </van-tabbar>
  </div>
</template>

<script>
export default {
  data() {
    return {
      active: 0,
      websocket: null,

      user: {},
      message: 0,
    };
  },
  created() {
    this.myaxios(this.host + "shops/userinfo/", "get",{
      user_id:localStorage.getItem('id'),
      user_type:localStorage.getItem('user_type')
    }).then((data) => {
      console.log(data);
      if (data.errcode == 0) {
        this.$toast.success(data.msg);
        this.user = data.data;
        localStorage.setItem("user_list", JSON.stringify(this.user));
        // this.$store.commit('setUser',this.user)
        this.init()
      } else {
        this.$toast.fail(data.msg);
      }
    });
  },
  destroyed() {
    this.websock.close(); //离开路由之后断开websocket连接
  },
  methods: {
    // 获取用户信息
    initWebSocket() {
      //初始化weosocket
      const wsuri = "ws://127.0.0.1:8000/ws/user/" + this.user.id + "_2/";
      this.websock = new WebSocket(wsuri);

      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onmessage = this.websocketonmessage;
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      console.log("websocket连接成功");
      console.log(this.$store.state.websocket);
    },
    websocketonerror() {
      //连接建立失败重连
      this.initWebSocket();
    },
    websocketonmessage(e) {
      console.log("接收消息", e.data);
      let data = eval("(" + e.data + ")"); //解析对象
      const redata = JSON.parse(e.data); //数据接收

      this.message++;

      // 缓存消息
      let chat = "chat_" + data.chat_id;
      let chat_message = localStorage.getItem(chat);
      if (chat_message) {
        chat_message = JSON.parse(chat_message);
      } else {
        chat_message = [];
      }
      chat_message.push(data);
      localStorage.setItem(chat, JSON.stringify(chat_message));
    },
    websocketsend(Data) {
      //数据发送
      this.websock.send(Data);
    },
    websocketclose(e) {
      //关闭
      console.log("断开连接", e);
    },
  },
};
</script>

<style>
</style>